import { createRouter,createWebHistory} from "vue-router";
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import ColumnDetail from "@/views/ColumnDetail.vue";
import CreatePost from "@/views/CreatePost.vue";
import Register from "@/views/Register.vue";
import ArticleDetail from "@/views/ArticleDetail.vue";
import store from "@/store/store";
import httpInstance from "@/axios";
const routerHisrory = createWebHistory()
const router = createRouter({
    history:routerHisrory,
    routes:[
        {
            path:'/',
            name:'home',
            component:Home,
        },
        {
            path:'/login',
            name:'login',
            component:Login,
            meta:{
                //重定向，当用户已经登录过后再点击登录时需要进行重定向
                redirectAlreadyLogin:true
            }
        },
        {
            path:'/register',
            name:'register',
            component:Register,

        },
        {
            path:'/column/:id',
            name:'column',
            component:ColumnDetail,
        },
        {
            path:'/create',
            name:'create',
            component:CreatePost,
            meta:{
                requiredLogin:true
            }
        },
        {
            path:'/article/:id',
            name:'article',
            component:ArticleDetail
        }
    ]
})
//设置一个全局前置路由守卫
router.beforeEach((to, from, next) => {
    const { user, token } = store.state
    const { redirectAlreadyLogin, requiredLogin } = to.meta
    //当用户已经进行登录
    if (user.isLogin) {
        if (redirectAlreadyLogin) {
            next('/')
        } else {
            next()
        }
    } 
    //当用户未登录时
    else {
        //检查token字段，是否存在，若存在，则直接请求当前用户的信息
        if(token){
            //发起请求时需要携带头部字段
            httpInstance.defaults.headers.common.Authorization = `Bearer ${token}`
            store.dispatch('fetchCurrentUser').then(()=>{
                //若请求成功后，在点击登录，则进行重定向
                if(redirectAlreadyLogin){
                    next('/')
                }
                //若点击跳转到其他的页面，直接进行跳转
                else{
                    next()
                }
            }).catch((e)=>{
                //若请求数据失败，则显示错误的信息，然后到登录页面
                localStorage.removeItem('token')
                next('/login')
                console.log(e)
            })
        }
        //当没有token字段时，判断是否需要登录
        else{
            if(requiredLogin){
                next('/login')
            }
            else{
                next()
            }
        }
    }
})
export default router